package com.tc.juc.pack08;

import lombok.extern.slf4j.Slf4j;
import sun.rmi.runtime.Log;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * @Auther: tianchao
 * @Date: 2021/10/17 20:52
 * @Description:
 */
@Slf4j
public class TestTimer {
    public static void main(String[] args) {
        //testTimer();
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.info("debug...");
//        pool.scheduleAtFixedRate(()->{
//            log.info("running...");
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        },2,1,TimeUnit.SECONDS);
//        pool.scheduleWithFixedDelay(()->{
//            log.info("running...");
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        },2,1,TimeUnit.SECONDS);
        method2(pool);
    }

    private static void method2(ScheduledExecutorService pool){
        ScheduledFuture<?> task1 = pool.schedule(() -> {
            log.info("task1");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 1 / 0;
        }, 1, TimeUnit.SECONDS);
        try {
            task1.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        pool.schedule(()->{
            log.info("task2");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, TimeUnit.SECONDS);
    }


    private static void testTimer() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("task1");
                int i = 1/0;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 1000);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("task2");
            }
        }, 1000);
    }
}
